<template>
  <div class="avatar">
    <div class="avatar-left">
      <div v-show="!options.img">
        <div class="avatar-upload">
          <el-upload drag action="#" :on-change="uploads" accept=".png , .jpg">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">拖拽文件上传 或 <em>点击上传</em></div>
          </el-upload>
        </div>
      </div>

      <div v-show="options.img" class="avatar-left-crop">
        <vueCropper
          ref="cropper"
          :img="options.img"
          :autoCrop="options.autoCrop"
          :fixedBox="options.fixedBox"
          :canMoveBox="options.canMoveBox"
          :autoCropWidth="options.autoCropWidth"
          :autoCropHeight="options.autoCropHeight"
          :centerBox="options.centerBox"
          @realTime="realTime"
        >
        </vueCropper>
      </div>
    </div>
    <div class="border-line"></div>
    <div class="avatar-right">
      <div class="avatar-right-div" :style="previewsDiv.style">
        <div
          v-show="options.img"
          :class="previews.div"
          :style="previewsDiv.zoomStyle"
          class="avatar-right-previews"
        >
          <img :src="previews.url" :style="previews.img" />
        </div>
        <div
          v-show="options.img"
          class="text"
          style="margin-left: 36px; margin-top: 10px"
        >
          预览头像
        </div>

        <div v-show="!options.img">
          <div><el-avatar :size="100" :src="circleUrl" /></div>
          <div class="text">当前头像</div>
        </div>
      </div>
    </div>
  </div>
  <div class="avatar-footer">
    <div class="text">
      建议图片上传：大小100 * 100像素支持JPG、PNG等格式，图片需小于2M
    </div>
    <div v-if="!options.img">
      <el-button type="primary" class="button" disabled>更新</el-button>
    </div>
    <div v-else>
      <el-button type="primary" class="button" @click="getCrop">更新</el-button>
    </div>
  </div>
</template>

<script>
import UserApi from '@/api/core/User'
import Cookie from 'js-cookie'
export default {
  name: 'UserAvatar',
  data() {
    return {
      circleUrl:
        'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      //实时预览图片样式
      previewsDiv:
        //108px 预览样式
        {
          style: {
            width: '100px',
            height: '100px',
            margin: '0 auto',
          },
          zoomStyle: {
            zoom: 1.5,
          },
        },
      //实时预览数据
      previews: {},

      //裁剪配置信息
      options: {
        img: '', //图片地址
        autoCrop: true, //是否默认生成截图框
        canMove: false, //上传图片是否可以移动
        fixedBox: true, //固定截图框大小
        canMoveBox: true, //截图框能否拖动
        centerBox: true, //截图框是否被限制在图片里面
        mode: 'cover',
        autoCropWidth: 100, //默认生成截图框宽度
        autoCropHeight: 100, //默认生成截图框高度
      },
    }
  },

  created() {
    this.circleUrl = Cookie.get('avatar')
  },

  methods: {
    //获取用户信息
    getUserInfo() {
      UserApi.getUserInfo().then((response) => {
        this.circleUrl = response.data.userInfo.avatarUrl
        Cookie.set('avatar', this.circleUrl)
        this.$router.go(0)
      })
    },

    //实时预览数据
    realTime(data) {
      this.previews = data
    },

    //读取原图
    uploads(file) {
      const isIMAGE =
        file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'

      if (!isIMAGE) {
        this.$message.error('请选择 jpg、png 格式的图片！')
        return false
      }

      const size = file.raw.size / 1024 / 1024
      if (size > 2) {
        this.$message.error('上传图片大小不能超过 2MB')
        return false
      }

      let reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = (e) => {
        this.options.img = e.target.result //base64
      }
    },

    //获取截图信息 提交请求
    getCrop() {
      // 获取截图的 base64 数据
      this.$refs.cropper.getCropData((data) => {
        const imgFile = this.base64ImgtoFile(data)
        let formData = new FormData()
        formData.append('avatar', imgFile)
        UserApi.updataAvatar(formData)
          .then(() => {
            this.getUserInfo()
          })
          .catch((error) => {
            this.$message.error(error.message)
          })
      })
    },

    //base64转换为图片
    base64ImgtoFile(dataurl, filename = 'file') {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      })
    },
  },
}
</script>

<style scoped>
.avatar {
  margin-top: 130px;
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  align-items: center;
}
.avatar-left {
  width: 350px;
  height: 200px;
}
.avatar-left-crop {
  width: 350px;
  height: 200px;
}
.border-line {
  height: 182px;
  width: 1px;
  background: #e5e9ef;
  float: left;
}

.avatar-right {
  width: 200px;
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}
.avatar-right .avatar-right-div {
  border-radius: 50%;
}
.avatar-right .avatar-right-previews {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
}
.avatar-right .text {
  margin-left: 15px;
  margin-top: 3px;
  line-height: 16px;
  color: #99a2aa;
}
.avatar-upload {
  width: 300px;
}
.avatar-footer {
  margin-top: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.avatar-footer .text {
  line-height: 16px;
  color: #99a2aa;
}
.avatar-footer .button {
  margin-top: 15px;
  width: 80px;
}
</style>
